// 注意：保存视频只支持保存编码为:H264格式的视频，所以请提前约定好视频格式
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <Photos/Photos.h>

// Unity 提供的消息发送接口
extern void UnitySendMessage(const char* obj, const char* method, const char* msg);

extern "C"
{
    // 保存图片到相册
    void SaveImage(const char* path)
    {
        NSString* filePath = [NSString stringWithUTF8String:path];
        UIImage* image = [UIImage imageWithContentsOfFile:filePath];
        if (!image) return; // 如果图片为空直接返回

        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusAuthorized)
        {
            // 已授权，直接保存
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Image Saved");
                }else{
                    UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Save fail!!");
                }
            }];
        }
        else if (status == PHAuthorizationStatusNotDetermined)
        {
            // 未确定授权状态，请求权限
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized)
                {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback",  "Image Saved");
                        }else{
                            UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Save fail!!");
                        }
                    }];
                }
            }];
        }
        else if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted)
        {
            // 用户拒绝或受限，引导用户到设置页开启权限
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            });
        }
    }

    // 保存视频到相册
    void SaveVideo(const char* path)
    {
        NSString* filePath = [NSString stringWithUTF8String:path];
        NSURL* videoURL = [NSURL fileURLWithPath:filePath];
        if (!videoURL) return; // 如果视频路径无效直接返回

        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusAuthorized)
        {
            // 已授权，直接保存
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (success) {
                    UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Video Saved");
                }else{
                    UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Save fail!!");
                }
            }];
        }
        else if (status == PHAuthorizationStatusNotDetermined)
        {
            // 未确定授权状态，请求权限
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized)
                {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        if (success) {
                            UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback",  "Video Saved");
                        }else{
                            UnitySendMessage("NativeMsgReceiver", "SaveAssetToAlbumCallback", "Save fail!!");
                        }
                    }];
                }
            }];
        }
        else if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted)
        {
            // 用户拒绝或受限，引导用户到设置页开启权限
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            });
        }
    }
}